import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, Table, Space, message, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import { history, useLocation } from 'umi';
import { getUsers, UserType } from '@/services/demo/UserController';

const UserListPage: React.FC = () => {
  const [dataSource, setDataSource] = useState<UserType[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const location = useLocation();

  // 获取用户数据
  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await getUsers();
      console.log('API Response:', response);
      
      // 直接使用响应数据，因为我们已经定义了正确的类型
      setDataSource(response || []);
    } catch (error) {
      console.error('Failed to fetch users:', error);
      message.error('获取用户列表失败');
      setDataSource([]);
    } finally {
      setLoading(false);
    }
  };

  // 监听URL参数变化，刷新数据
  useEffect(() => {
    fetchUsers();
  }, [location.search]);

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '平台',
      dataIndex: ['platform', 'name'],
      key: 'platformName',
      render: (platformName: string) => platformName || '-',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      render: (roles: any[]) => (
        <>
          {roles && roles.length > 0 ? (
            <Space size={[0, 4]} wrap>
              {roles.map((role) => (
                <Tag color="blue" key={role.id}>
                  {role.name}
                </Tag>
              ))}
            </Space>
          ) : (
            <span>无角色</span>
          )}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled: boolean) => (
        <Tag color={enabled ? 'green' : 'red'}>
          {enabled ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => history.push(`/user/detail/${record.id}`)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => message.warning('删除功能待实现')}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '用户列表',
        extra: [
          <Button 
            key="add" 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => history.push('/user/create')}
          >
            添加用户
          </Button>,
        ],
      }}
    >
      <Card>
        <Table 
          dataSource={dataSource} 
          columns={columns} 
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      </Card>
    </PageContainer>
  );
};

export default UserListPage;
